/**
 * Copyright (c) 2013 An Yaming,  All Rights Reserved
 */
package so.shanku.essential.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil.IGetServicesDataCallBack;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.adapter.HasClickAdapter;
import so.shanku.essential.adapter.ShoppingUserRecipientAdapter;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.utils.Utils;
import so.shanku.essential.view.WihteRoundCornersDialog;
import striveen.util.used.view.view.XListView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tanghuan
 * @ClassName: ShoppingUserRecipientActivity
 * @Description: TODO(订单收货人信息)
 * @date 2014年12月3日 下午7:53:16
 */
public class ShoppingUserRecipientActivity extends BaseUIActivity implements AdapterView.OnItemLongClickListener, AdapterView.OnItemClickListener {
    /**
     * 订单收货人信息列表
     */
    @ViewInject(id = R.id.s_u_r_lmlv_recipient_list)
    private XListView lmlv_shouhuaren;
    @ViewInject(id = R.id.add_address_layout, click = "add_address_layout_click")
    private LinearLayout add_address_layout;
    /**
     * 收货人列表数据
     */
    private List<JsonMap<String, Object>> data_shouhuaren;
    /**
     * 收货人列表数据适配器
     */
    private ShoppingUserRecipientAdapter adapter_shouhuaren;
    /**
     * 选中的收货人信息
     */
//	@ViewInject(id = R.id.s_u_r_i_ib_chooice, click = "chooiceInfo")
//	private ImageButton ib_chooice;


    // activity之间跳转的参数
    private String activity_parameter;

    private String addressId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_user_recipient_list);
        setCenter_title(R.string.user_msg);
//		R.drawable.shopping_user_recipient_address_add,
        Intent intent = getIntent();
        activity_parameter = intent.getStringExtra(ExtraKeys.Key_Msg1);
        getData_ShouHuoRenList();
        lmlv_shouhuaren.setPullRefreshEnable(false);
        lmlv_shouhuaren.setPullLoadEnable(false);
        lmlv_shouhuaren.setOnItemClickListener(this);
        lmlv_shouhuaren.setOnItemLongClickListener(this);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            if (data_shouhuaren == null || data_shouhuaren.size()<1) {
                if ("UserActivity".equals(activity_parameter)) {
                    getData_ShouHuoRenList();
                } else {
                    setResult(Activity.RESULT_OK, data);
                    mContext.finish();
                }
            } else {
                getData_ShouHuoRenList();
            }
        }
    }

    @Override
    public void finish() {

        if (adapter_shouhuaren != null) {

            int selectPosition = adapter_shouhuaren.getSelectPosition();
            if (selectPosition != -1) {

                Intent intent = getIntent();
                intent.putExtra(
                        ExtraKeys.Key_Msg1,
                        data_shouhuaren.get(selectPosition).getStringNoNull(
                                "consignee"));
                intent.putExtra(
                        ExtraKeys.Key_Msg2,
                        data_shouhuaren.get(selectPosition).getStringNoNull(
                                "phone"));
                intent.putExtra(
                        ExtraKeys.Key_Msg3,
                        data_shouhuaren.get(selectPosition).getStringNoNull(
                                "consigneeAddress"));
                intent.putExtra(
                        ExtraKeys.Key_Msg4,
                        data_shouhuaren.get(selectPosition).getStringNoNull(
                                "id"));
                setResult(RESULT_OK, intent);

            }
        }
        super.finish();
    }

    /**
     * 选中事件
     *
     * @param v
     */
    public void chooiceInfo(View v) {

    }

    /**
     * 为收货人列表设定数据适配器
     */
    private void setAdatper_shouHuoRenList(List<JsonMap<String, Object>> data) {
        this.data_shouhuaren = data;
        int resId = 0;
        if (data_shouhuaren != null) {
            if ("UserActivity".equals(activity_parameter)) {
                resId = 1;
            }
            adapter_shouhuaren = new ShoppingUserRecipientAdapter(this,
                    data_shouhuaren, R.layout.item_shopping_user_recipient,
                    new String[]{"consignee", "phone", "consigneeAddress"},
                    new int[]{R.id.i_s_u_r_i_tv_recipient_name,
                            R.id.i_s_u_r_i_tv_recipient_phone,
                            R.id.i_s_u_r_i_tv_recipient_address}, resId,
                    R.id.i_s_u_r_i_ib_chooice, clickListener2);
            lmlv_shouhuaren.setAdapter(adapter_shouhuaren);
        }
    }

    /**
     * 获取服务器守护人列表
     */
    private void getData_ShouHuoRenList() {
        loadingToast.show();

        Map<String, Object> params = new HashMap<String, Object>();
        params.put(GetDataQueue.Params_key, GetDataConfing.Key_addressbyuserid);
        params.put("userName", Utils.getUserAccount(this));
        GetDataQueue queue = new GetDataQueue();
        queue.setCallBack(callBack);
        queue.setActionName(GetDataConfing.GetAction_GetAddresslistByUsername);
        queue.setWhat(GetDataConfing.what_GetAddresslistByUsername);
        queue.setParamsNoJson(params);
        getDataUtil.getData(queue);
    }

    /**
     * 调用服务删除地址信息
     */
    private void getData_deleteShouHuoRen() {
        if (addressId.equals(activity_parameter)) {
            toast.showToast(R.string.address_using);
            return;
        }
        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(GetDataQueue.Params_key,
                GetDataConfing.Key_userDeleteAddressById);
        params.put("Id", addressId);

        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_userDeleteAddressById);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_userDeleteAddressById);
        getDataUtil.getData(queue);
    }


    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {

        @Override
        public void onLoaded(GetServicesDataQueue entity) {
            if (entity.isOk()) {
                if (entity.what == GetDataConfing.what_GetAddresslistByUsername) {
                    if (ShowGetDataError.isOK(
                            ShoppingUserRecipientActivity.this,
                            entity.getInfo())) {
                        setAdatper_shouHuoRenList(JsonParseHelper
                                .getJsonMap_List_JsonMap(entity.getInfo(),
                                        JsonKeys.Key_Info));
                    }
                } else if (entity.what == GetDataConfing.What_userDeleteAddressById) {
                    toast.showToast(JsonParseHelper.getAttribute(
                            entity.getInfo(), new String[]{JsonKeys.Key_Msg}));
                    getData_ShouHuoRenList();
                }
            } else {
                ShowGetDataError
                        .showNetError(ShoppingUserRecipientActivity.this);
            }
            loadingToast.dismiss();

        }
    };

    /**
     * 添加地址的事件监听
     */
    public void add_address_layout_click(View v) {
        Intent intent = new Intent(ShoppingUserRecipientActivity.this,
                ShoppingNewRecipientAddressActivity.class);
        startActivityForResult(intent, 1);
    }

    /**
     * 处理选中事件
     */
    private HasClickAdapter.ItemOneViewClickListener clickListener2 = new HasClickAdapter.ItemOneViewClickListener() {

        @Override
        public void onClick(View v, int position) {
            int selectPosition = adapter_shouhuaren.getSelectPosition();
            if (selectPosition != -1) {
                JsonMap<String, Object> d = (JsonMap<String, Object>) adapter_shouhuaren
                        .getItem(selectPosition);
                d.put("isSelect", false);
            }
            JsonMap<String, Object> d2 = (JsonMap<String, Object>) adapter_shouhuaren
                    .getItem(position);
            d2.put("isSelect", true);
            adapter_shouhuaren.notifyDataSetChanged();
            finish();
        }
    };

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
        addressId = data_shouhuaren.get(position).getStringNoNull("id");
        showDialog();
        return true;
    }

    WihteRoundCornersDialog builder;

    private void showDialog() {
        builder = new WihteRoundCornersDialog(this,
                R.style.ExitDialogStyle, 2, callBackdialog);
        builder.setTitletext(R.string.user_like_cancle_delete_address);
        builder.setMessagetext(R.string.user_like_confirm_cancle_delete_address);
        builder.setButtonText(R.string.cancel, R.string.ensure);
        builder.show();
    }

    private WihteRoundCornersDialog.DialogCallBack callBackdialog = new WihteRoundCornersDialog.DialogCallBack() {

        @Override
        public void bttonclick(int index) {
            builder.dismiss();
            switch (index) {
                case 1:

                    break;
                case 2:
                    getData_deleteShouHuoRen();
                    break;
                default:
                    break;
            }
        }

        @Override
        public void bttonclick(int index, int what) {

        }

    };

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        Intent intent = new Intent(ShoppingUserRecipientActivity.this,
                ShoppingNewRecipientAddressActivity.class);
        intent.putExtra(ExtraKeys.Key_Msg1, data_shouhuaren.get(position)
                .getString("id"));
        intent.putExtra("userName", data_shouhuaren.get(position).getStringNoNull("consignee"));
        intent.putExtra("phone", data_shouhuaren.get(position).getStringNoNull("phone"));
        intent.putExtra("consigneeAddress", data_shouhuaren.get(position).getStringNoNull("consigneeAddress"));
        if (data_shouhuaren.get(position).getString("id") != null) {
            intent.putExtra(ExtraKeys.Key_Msg2, data_shouhuaren.get(position)
                    .getString("district"));
            intent.putExtra(ExtraKeys.Key_Msg3, data_shouhuaren.get(position)
                    .getString("city"));
        }

        startActivityForResult(intent, 1);
    }
}
